﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Auto_Buy.Component;
using Quartz;

namespace Auto_Buy
{
    public class AutoBuyJob: IJob
    {
        private const string ProductTitle = "双节天天赚";

        private static readonly Random Random = new Random();
        public async Task Execute(IJobExecutionContext context)
        {
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine();
            var second = Random.Next(35, 85);
            var datetime = context.NextFireTimeUtc.HasValue
                ? context.NextFireTimeUtc.Value.LocalDateTime.ToString("HH:mm:ss",CultureInfo.InvariantCulture)
                : "";
            Console.WriteLine("本次沉睡 {0} 秒, 下次任务开始时间 {1}", second, datetime);
            await Task.Delay(second * 1000);

            //产品列表
            var list = await ProductList.GetListByType(1);
            if (list == null || list.Count == 0)
            {
                Console.WriteLine("empty list");
                return;
            }
            var product = list.FirstOrDefault(it => it.Title == ProductTitle);
            if (product == null)
            {
                Console.WriteLine("No "+ ProductTitle);
                //移除本条任务
                await context.Scheduler.DeleteJob(context.JobDetail.Key);
                return;
            }
            Console.WriteLine($"{ProductTitle} Id:{product.Id}, 份额：{product.RemainingShares}, 起价:{product.StartBuyPrice}");
 

            //购买记录
            var records = await ProductBuyRecord.BuyRecord(product.Id);
            foreach (var record in records)
            {
                Console.WriteLine(record.Phone);
            }

            //匹配用户
            var user1 = UserSession.UserInfos.FirstOrDefault(it => it.IsAvailable && records.All(r => r.Phone != it.CoverPhone));
            if (user1 == null)
            {
                Console.WriteLine("所有的用户都在第一页显示了");
                return;
            }

            Console.WriteLine("匹配用户：" + user1.Phone);

            //login
            if (string.IsNullOrEmpty(user1.Token))
            {
                //登录
                var loginResult = await UserLogin.Login(user1.Phone, user1.Pwd);
                if (loginResult != null && !string.IsNullOrEmpty(loginResult.Token))
                {
                    user1.Token = loginResult.Token;
                    Console.WriteLine("登录成功");
                }
                else
                {
                    Console.WriteLine("登录失败");
                    return;
                }
            }
            //buy
            var share = UserSession.RandomShare();
            if (product.RemainingShares < share)
            {
                share = (int) product.RemainingShares;
            }

            var buyResult = await ProductBuy.Buy(product.Id, share, user1.TradePwd, user1.Token);
            if (buyResult.Id > 0)
            {
                Console.WriteLine("购买成功 Id:{0}", buyResult.Id);
            }
            else
            {
                if (buyResult.Code != null && buyResult.Code == "101")
                {
                    user1.Token = string.Empty;
                }

                if (!string.IsNullOrEmpty(buyResult.Message))
                {
                    if (buyResult.Message == "产品已售罄")
                    {
                        //移除本条任务
                        await context.Scheduler.DeleteJob(context.JobDetail.Key);
                        return;
                    }
                    if (buyResult.Message == "您不符购买条件，请查看活动规则")
                    {
                        user1.IsAvailable = false;
                    }
                    if (buyResult.Message == "购买份额超过产品购买上限")
                    {
                        user1.IsAvailable = false;
                    }
                }
                Console.WriteLine("购买失败 Message:{0}", buyResult?.Message);
            }
        }
    }
}
